package logger

import (
	"sync/atomic"
)

type IContextPool interface {
	PoolSize() int

	Get() *Context
	Put(ctx *Context)
}

type ContextPool struct {
	pool     chan *Context
	poolSize int

	NewCnt int64
}

func newContextPool(poolSize int) *ContextPool {
	p := &ContextPool{
		pool:     make(chan *Context, poolSize),
		poolSize: poolSize,
	}

	return p
}

func (p *ContextPool) PoolSize() int {
	return p.poolSize
}

func (p *ContextPool) Get() *Context {
	select {
	case ctx := <-p.pool:
		return ctx
	default:
		//一定要成功获得, 不能等待
		atomic.AddInt64(&p.NewCnt, 1)
		return NewContext(p)
	}
}

func (p *ContextPool) Put(ctx *Context) {
	select {
	case p.pool <- ctx:
	default:
		//throw to gc
	}
}
